﻿using MDT.LifeSewagePlatform.Conmmon;
using MDT.LifeSewagePlatform.Entity;
using MDT.LifeSewagePlatform.IRepository;
using Microsoft.Extensions.Configuration;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MDT.LifeSewagePlatform.Repository
{
    public class BuilderWordReportRepository : IBuilderWordReportRepository
    {
        [Autowired]
        private IManagerWord managerWord { get; set; }

        [Autowired]
        private IConfiguration _configuration { get; set; }
        [Autowired]
        private SystemConfigEntity systemConfigEntity { get; set; }
        /// <summary>
        /// 第一段文字
        /// </summary>
        /// <param name="CityName"></param>
        /// <param name="Year"></param>
        /// <param name="Quarter"></param>
        /// <param name="areaAreaData"></param>
        /// <returns></returns>
        public async Task FirstSection(int Year, int Quarter, List<DrugDetailReprot> areaAreaData)
        {
            await managerWord.CreateDocAsync();

            #region  第一章
            await managerWord.CreatePAsync(WordTemplate.GetWorldTitile());
            await managerWord.CreatePAsync(WordTemplate.GetPingGuBaoGao());
            await managerWord.CreatePAsync(
                WordTemplate.GetQuarter(new string[] { Year.ToString(), Quarter.MapMaxNumber() }),
                 (p, run) =>
                 {
                     run.FontSize = 16;
                     run.FontFamily = "楷体";
                     p.Alignment = ParagraphAlignment.CENTER;
                 });
            await managerWord.CreatePAsync("",
              (p, run) =>
              {
                  //Times New Roman
                  run.FontSize = 14;
                  run.FontFamily = "Times New Roman";
                  for (int i = 0; i < 8; i++)
                  {
                      p.Alignment = ParagraphAlignment.CENTER;
                      run.AddCarriageReturn();
                  }
              });
            await managerWord.CreatePAsync(WordTemplate.GetComponyName(),
             (p, run) =>
             {
                 run.IsBold = true;
                 run.FontSize = 14;
                 run.FontFamily = "宋体 (中文正文)";
                 p.Alignment = ParagraphAlignment.CENTER;
                 run.AddCarriageReturn();
                 run.AppendText(WordTemplate.GetDate(new string[] { DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString() }));
             });


            await managerWord.CreatePAsync(WordTemplate.GetDate(new string[] { DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString() }),
           (p, run) =>
           {
               run.IsBold = true;
               run.FontSize = 14;
               run.FontFamily = "宋体 (中文正文)";
               p.Alignment = ParagraphAlignment.CENTER;
           });

            await managerWord.CreatePAsync("",
         (p, run) =>
         {
             run.FontSize = 14;
             run.FontFamily = "宋体 (中文正文)";
             p.Alignment = ParagraphAlignment.CENTER;
             run.AddBreak();
             run.AddCarriageReturn();
             run.AddBreak();
         });

            await managerWord.CreatePAsync(WordTemplate.Get001(),
            (p, run) =>
            {
                managerWord.OneTitle(p, run);
                p.Alignment = ParagraphAlignment.CENTER;

            });

            await managerWord.CreatePAsync(WordTemplate.Get002(),
             (p, run) =>
             {
                 managerWord.OneTitle(p, run);

             });

            await managerWord.CreatePAsync(WordTemplate.Get003(),
            (p, run) =>
            {
                managerWord.Content(p, run);
            });

            await managerWord.CreatePAsync(WordTemplate.Get004(),
         (p, run) =>
         {
             managerWord.Content(p, run);

         });
            await managerWord.CreatePAsync(WordTemplate.Get005(),
             (p, run) =>
             {

                 managerWord.Content(p, run);
                 p.Alignment = ParagraphAlignment.CENTER;
                 managerWord.CreateTable(areaAreaData.Count + 1, 2, (table, doc) =>
                 {
                     table.Width = 1000 * 3;
                     table.SetColumnWidth(0, 800); /* 设置列宽 */
                     table.SetColumnWidth(0, 2200); /* 设置列宽 */
                     table.GetRow(0).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, "县（区）"));
                     table.GetRow(0).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, "污水厂"));

                     for (int i = 1; i <= areaAreaData.Count; i++)
                     {
                         if (string.IsNullOrEmpty(areaAreaData[i - 1].AreaName) == false && areaAreaData[i - 1].AreaName != "市")
                         {
                             table.GetRow(i)
                           .GetCell(0)
                           .SetParagraph(managerWord.SetCellText(doc, table, areaAreaData[i - 1].AreaName));
                             table.GetRow(i)
                              .GetCell(1)
                              .SetParagraph(managerWord.SetCellText(doc, table, areaAreaData[i - 1].MonitoringSite));
                         }

                     }
                 });



             });

            await managerWord.CreatePAsync(WordTemplate.Get006(),
                 (p, run) =>
                 {
                     managerWord.Content(p, run);

                 });

            await managerWord.CreatePAsync(WordTemplate.Get007(),
            (p, run) =>
            {
                managerWord.Content(p, run);
            });

            await managerWord.CreatePAsync(WordTemplate.Get008(),
            (p, run) =>
            {
                managerWord.Content(p, run);

            });

            #endregion
        }
        /// <summary>
        /// 第二段文字
        /// </summary>
        public async Task SecondSection()
        {
            #region
            await managerWord.CreatePAsync(WordTemplate.Get0037(), (p, r) =>
            {

                managerWord.OneTitle(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0038(), (p, r) =>
            {

                managerWord.TwoTitle(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0039(), (p, r) =>
            {

                managerWord.Content(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0040(), (p, r) =>
            {

                managerWord.TwoTitle(p, r);
            });
            await managerWord.CreatePAsync(WordTemplate.Get0041(), (p, r) =>
            {

                managerWord.Content(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0042(), (p, r) =>
            {

                managerWord.TwoTitle(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0043(), (p, r) =>
            {

                managerWord.Content(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0044(), (p, r) =>
            {

                managerWord.TwoTitle(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0045(), (p, r) =>
            {

                managerWord.Content(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0046(), (p, r) =>
            {

                managerWord.TwoTitle(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0047(), (p, r) =>
            {

                managerWord.Content(p, r);
            });
            #endregion
        }
        /// <summary>
        /// 第三段文字
        /// </summary>
        /// <param name="CityName"></param>
        /// <param name="areaData"></param>
        /// <param name="ReducedTotal"></param>
        /// <returns></returns>

        public async Task ThirdSection(List<DrugDetailReprot> areaData, double ReducedTotal)
        {
            #region 第三章
            await managerWord.CreatePAsync(WordTemplate.Get009(),
            (p, run) =>
            {
                managerWord.OneTitle(p, run);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0010(),
            (p, run) =>
            {
                managerWord.Content(p, run);

            });
            await managerWord.CreatePAsync(WordTemplate.Get0011(),
           (p, run) =>
           {
               managerWord.Content(p, run);

           });
            await managerWord.CreatePAsync(WordTemplate.Get0012(
                areaData.Select(t => new PieView() { Name = t.AreaName, Value = t.ReducedTotal }).ToList(),
                ReducedTotal),
            (p, run) =>
            {
                managerWord.Content(p, run);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0013(
               areaData.Select(t => new PieView() { Name = t.AreaName, Value = t.ReducedTotal }).ToList()
               ),
           (p, run) =>
           {
               run.AddTab();
               managerWord.Content(p, run);
               run.IsBold = true;
           });


            #endregion
        }

        /// <summary>
        /// 第四段
        /// </summary>
        /// <param name="CityName"></param>
        /// <param name="drugDetailGroupData"></param>
        /// <param name="CityData"></param>
        /// <param name="AreaData"></param>
        /// <param name="AreaDataPast"></param>
        /// <param name="CityDataPast"></param>
        /// <returns></returns>
        public async Task FourthSection(List<DrugDetailReprot>
            drugDetailGroupData, DrugDetailReprot CityData, List<DrugDetailReprot> AreaData
            , List<DrugDetailReprot> drugDetailPast)
        {

            string ImgPath = _configuration["ImgPath"];
            // _config["ImgPath"];



            #region 第四章
            await managerWord.CreatePAsync(WordTemplate.Get0018(),
           (p, run) =>
           {

               managerWord.OneTitle(p, run);

           });
            await managerWord.CreatePAsync(WordTemplate.Get0019(),
             (p, run) =>
             {
                 p.Alignment = ParagraphAlignment.CENTER;

                 managerWord.Content(p, run);
                 managerWord.CreateTable(drugDetailGroupData.Count + 2, 8, (table, doc) =>
                 {


                     table.Width = 700 * 8;
                     table.SetColumnWidth(0, 700); /* 设置列宽 */
                     table.SetColumnWidth(1, 700); /* 设置列宽 */
                     table.SetColumnWidth(2, 700); /* 设置列宽 */
                     table.SetColumnWidth(3, 700); /* 设置列宽 */
                     table.SetColumnWidth(4, 700); /* 设置列宽 */
                     table.SetColumnWidth(5, 700); /* 设置列宽 */
                     table.SetColumnWidth(6, 700); /* 设置列宽 */
                     table.SetColumnWidth(7, 700); /* 设置列宽 */


                     table.GetRow(0).MergeCells(1, 7); /* 合并行 */
                     table.GetRow(0).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, "消耗量（毫克/天/千人）"));


                     CT_Tc cttc = table.GetRow(0).GetCell(0).GetCTTc();
                     CT_TcPr ctPr = cttc.AddNewTcPr();
                     ctPr.AddNewVMerge().val = ST_Merge.restart;//合并行
                     ctPr.AddNewVAlign().val = ST_VerticalJc.center;//垂直


                     CT_Tc cttc_1 = table.GetRow(1).GetCell(0).GetCTTc();
                     CT_TcPr ctPr_1 = cttc_1.AddNewTcPr();
                     ctPr_1.AddNewVMerge().val = ST_Merge.@continue;//合并行
                     table.GetRow(0).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, "采样地点", 10));
                     Type type = typeof(DrugDetailReprot);
                     int index = 1;
                     foreach (var item in type.GetProperties().Where(t => t.PropertyType == typeof(double)))
                     {
                         string name = item.GetColName();
                         if (name.Contains("（"))
                         {
                             name = name.Substring(0, name.IndexOf("（"));
                         }
                         table.GetRow(1).GetCell(index).SetParagraph(managerWord.SetCellText(doc, table, name, 11));
                         index++;
                     }
                     for (int i = 2; i < drugDetailGroupData.Count + 2; i++)
                     {
                         if (i == drugDetailGroupData.Count + 1)
                         {
                             //最后一条数据
                             table.GetRow(i).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, "平均值"));
                             table.GetRow(i).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, CityData.Diamorphine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, CityData.Methylamphetamine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(3).SetParagraph(managerWord.SetCellText(doc, table, CityData.Ketamine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(4).SetParagraph(managerWord.SetCellText(doc, table, CityData.Cyclohexanone.SaveNumberPoint()));
                             table.GetRow(i).GetCell(5).SetParagraph(managerWord.SetCellText(doc, table, CityData.Ecstasy.SaveNumberPoint()));
                             table.GetRow(i).GetCell(6).SetParagraph(managerWord.SetCellText(doc, table, CityData.Cocaine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(7).SetParagraph(managerWord.SetCellText(doc, table, CityData.ReducedTotal.SaveNumberPoint()));

                         }
                         else
                         {
                             table.GetRow(i).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, AreaData[i - 2].AreaName));
                             table.GetRow(i).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, AreaData[i - 2].Diamorphine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, AreaData[i - 2].Methylamphetamine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(3).SetParagraph(managerWord.SetCellText(doc, table, AreaData[i - 2].Ketamine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(4).SetParagraph(managerWord.SetCellText(doc, table, AreaData[i - 2].Cyclohexanone.SaveNumberPoint()));
                             table.GetRow(i).GetCell(5).SetParagraph(managerWord.SetCellText(doc, table, AreaData[i - 2].Ecstasy.SaveNumberPoint()));
                             table.GetRow(i).GetCell(6).SetParagraph(managerWord.SetCellText(doc, table, CityData.Cocaine.SaveNumberPoint()));
                             table.GetRow(i).GetCell(7).SetParagraph(managerWord.SetCellText(doc, table, AreaData[i - 2].ReducedTotal.SaveNumberPoint()));

                         }
                     }

                 });

             });

            await managerWord.CreatePAsync(WordTemplate.Get0020(new string[] { "1", "折算总量" }),
             (p, run) =>
             {
                 managerWord.TwoTitle(p, run);

             });

            await managerWord.CreatePAsync(WordTemplate.Get0021(AreaData.OrderByDescending(t=>t.ReducedTotal).Select(t => new PieView() { Name = t.AreaName, Value = t.ReducedTotal }).ToList(), CityData.ReducedTotal),
           (p, run) =>
           {

               managerWord.Content(p, run);

           });
            
            managerWord.AddPic(@$"{ImgPath}\{CityData.CompanyID}\{CityData.Quarter}\col\ReducedTotal_area.png", 600, 400);

            await managerWord.CreatePAsync(WordTemplate.Get0022(managerWord.GetPicIndex(),"折算总量"),
                  (p, run) =>
                  {
                      run.FontSize = 12;
                      run.IsBold = false;
                      p.Alignment = ParagraphAlignment.CENTER;
                      run.FontFamily = "宋体";

                  });
            if (drugDetailPast != null && drugDetailPast.Count > 0)
            {
                foreach (var areaterm in drugDetailPast)
                {
                    await managerWord.CreatePAsync(WordTemplate.Get0023(CityData.ReducedTotal, areaterm.ReducedTotal, areaterm.Year, areaterm.Quarter,(eGroupGetDateType)systemConfigEntity.QuarterOrMonth,
                                     (sb, name,p) =>
                                     {
                                         sb.Append($"我市{name}折算总量{WordTemplate.ByNumberUpLow(p)}{p.SaveNumberPoint()}%；");
                                         bool isZero = false;
                                         string noSewageArea = string.Empty;
                                         for (int i = 0; i < AreaData.Count; i++)
                                         {
                                             double past = 0;
                                             if (areaterm.AreaDatas.Where(t => t.AreaID == AreaData[i].AreaID).Any())
                                             {
                                                 past = areaterm.AreaDatas.Where(t => t.AreaID == AreaData[i].AreaID).FirstOrDefault().ReducedTotal;
                                             }

                                             if (AreaData[i].ReducedTotal <= 0)
                                             {
                                                 isZero = true;
                                                 noSewageArea += AreaData[i].AreaName + ",";
                                                 //sb.Append($"{AreaData[i].AreaName},");
                                             }
                                             else if (past == 0)
                                             {
                                                 sb.Append($"{AreaData[i].AreaName}折算总量{WordTemplate.ByNumberUpLow(100)}{100.00}%；");
                                             }
                                             else
                                             {
                                                 double percent = AreaData[i].ReducedTotal.GetPercent(past);
                                                 sb.Append($"{AreaData[i].AreaName}折算总量{WordTemplate.ByNumberUpLow(percent)}{Math.Abs(percent).SaveNumberPoint()}%；");
                                             }
                                         }

                                         if (isZero)
                                         {
                                             string str = sb.ToString().StrRemove(true, 1) + $"{noSewageArea.StrRemove(true, 1)}在两次监测中均未检出明显的{name}消耗。。";
                                             sb.Clear();
                                             sb.Append(str);
                                         }
                                     },
                                     ""
                                     ),
                                      (p, run) =>
                                      {

                                          managerWord.Content(p, run);

                                      });
                }
            }



            Type type = typeof(DrugDetailReprot);
            int ix = 2;


            ////不同类型的毒品
            foreach (var item in type.GetProperties().Where(t => t.GetColName().Contains("（")))
            {

                if (double.TryParse(item.GetValue(CityData).ToString(), out double res))
                {
                    if (res > 0)
                    {
                        string propName = item.GetColName();
                        propName = propName.Substring(0, propName.IndexOf("（"));
                        await managerWord.CreatePAsync(WordTemplate.Get0020(new string[] { $"{ix}", propName }),
                        (p, run) =>
                        {

                            managerWord.TwoTitle(p, run);
                        });
                        await managerWord.CreatePAsync(WordTemplate.Get0024(AreaData.Select(t => new PieView() { Name = t.AreaName, Value = (double)item.GetValue(t) }).OrderByDescending(t=>t.Value).ToList(), res, propName),
                        (p, run) =>
                        {
                            run.FontSize = 14;
                            run.IsBold = false;
                            run.AddTab();
                            run.FontFamily = "宋体";
                        });
                        managerWord.AddPic(@$"{ImgPath}\{CityData.CompanyID}\{CityData.Quarter}\col\{item.Name}_area.png", 600, 370);

                        await managerWord.CreatePAsync(WordTemplate.Get0022(managerWord.GetPicIndex()),
                              (p, run) =>
                              {
                                  run.FontSize = 12;
                                  run.IsBold = false;
                                  p.Alignment = ParagraphAlignment.CENTER;
                                  run.FontFamily = "宋体";

                              });


                        ///////遍历多条历史季度数据
                        if (drugDetailPast != null && drugDetailPast.Any())
                        {
                            foreach (var areaTerm in drugDetailPast)
                            {
                                double.TryParse(item.GetValue(areaTerm).ToString(), out double resPast);
                                await managerWord.CreatePAsync(WordTemplate.Get0023(res, resPast, areaTerm.Year, areaTerm.Quarter, (eGroupGetDateType)systemConfigEntity.QuarterOrMonth,
                                        (sb, name,p) =>
                                        {
                                            sb.Append($"我市{name}平均消耗量{WordTemplate.ByNumberUpLow(p)}{p.SaveNumberPoint()}%；");
                                            bool isZero = false;
                                            string noSewagearea = string.Empty;
                                            for (int i = 0; i < AreaData.Count; i++)
                                            {
                                                double past = 0;
                                                if (areaTerm.AreaDatas.Where(t => t.AreaID == AreaData[i].AreaID).Any())
                                                {
                                                    double.TryParse(item.GetValue(areaTerm.AreaDatas.Where(t => t.AreaID == AreaData[i].AreaID).FirstOrDefault()).ToString(), out past);
                                                }
                                                double res = 0;
                                                double.TryParse(item.GetValue(AreaData[i]).ToString(), out res);
                                                if (res <= 0)
                                                {
                                                    isZero = true;
                                                    noSewagearea += AreaData[i].AreaName + ",";
                                                }
                                                else if (past == 0)
                                                {
                                                    sb.Append($"{AreaData[i].AreaName}{name}消耗量{WordTemplate.ByNumberUpLow(100)}{100.00}%；");
                                                }
                                                else
                                                {
                                                    double percent = res.GetPercent(past);
                                                    sb.Append($"{AreaData[i].AreaName}{name}消耗量{WordTemplate.ByNumberUpLow(percent)}{Math.Abs(percent).SaveNumberPoint()}%；");
                                                }
                                            }

                                            if (isZero)
                                            {
                                                string str = sb.ToString().StrRemove(true, 1) + $"{noSewagearea.StrRemove(true, 1)}在两次监测中均未检出明显的{name}消耗。。";
                                                sb.Clear();
                                                sb.Append(str);
                                            }
                                        }, propName
                                        ),
                                         (p, run) =>
                                         {

                                             managerWord.Content(p, run);
                                         });
                            }
                        }
                        ix++;
                    }
                }
            }

            #endregion
        }
        /// <summary>
        /// 第五段
        /// </summary>
        /// <param name="CityData"></param>
        /// <param name="GroupDrugData"></param>
        /// <param name="Quarter"></param>
        /// <param name="CompanyID"></param>
        /// <param name="AreaData"></param>
        /// <returns></returns>
        public async Task FivethSection(DrugDetailReprot CityData, List<DrugDetailReprot>
            GroupDrugData, int Quarter, int CompanyID, List<DrugDetailReprot> AreaData)
        {
            string ImgPath = _configuration["ImgPath"];
            #region 第五章
            await managerWord.CreatePAsync(WordTemplate.Get0014(),
                                (p, run) =>
                                {
                                    managerWord.OneTitle(p, run);

                                });
            for (int i = 0; i < GroupDrugData.Count; i++)
            {
                if (i == 0)
                {
                    await managerWord.CreatePAsync(WordTemplate.Get0015(new string[] { $"{i + 1}", CityData.CityName }),
                     (p, run) =>
                     {
                         managerWord.TwoTitle(p, run);
                         managerWord.AddPic(Path.Combine(ImgPath, CompanyID.ToString(), Quarter.ToString(), "pie", $"{CityData.AreaID}_city.png"), 600, 370);
                     });
                    await managerWord.CreatePAsync(WordTemplate.Get0016(new string[] { $"{managerWord.GetPicIndex()}", AreaData[i].AreaName }),
                    (p, run) =>
                    {
                        run.FontSize = 12;
                        run.IsBold = false;
                        run.FontFamily = "宋体";
                        p.Alignment = ParagraphAlignment.CENTER;
                    });

                    await managerWord.CreatePAsync(WordTemplate.Get0017(CityData),
                    (p, run) =>
                    {
                        managerWord.Content(p, run);
                    });
                }
                else
                {
                    await managerWord.CreatePAsync(WordTemplate.Get0015(new string[] { $"{i + 1}", AreaData[i - 1].AreaName }),
                    (p, run) =>
                    {
                        //run.FontSize = 12;
                        //run.IsBold = true;
                        //p.Style = "2";
                        //run.FontFamily = "宋体 ";
                        managerWord.TwoTitle(p, run);
                        managerWord.AddPic(Path.Combine(ImgPath, CompanyID.ToString(), Quarter.ToString(), "pie", $"{AreaData[i - 1].AreaID}_area.png"), 600, 400);
                    });
                    await managerWord.CreatePAsync(WordTemplate.Get0016(new string[] { $"{managerWord.GetPicIndex()}", AreaData[i - 1].AreaName }),
                    (p, run) =>
                    {
                        run.FontSize = 12;
                        run.IsBold = false;
                        run.FontFamily = "宋体";
                        p.Alignment = ParagraphAlignment.CENTER;
                    });

                    await managerWord.CreatePAsync(WordTemplate.Get0017(AreaData[i - 1], AreaData[i - 1].AreaName),
                    (p, run) =>
                    {
                        managerWord.Content(p, run);
                    });
                }


            }

            #endregion
        }

        public async Task SixthSection(DrugReport CityDrug, List<DrugReport> AreaDrug, DrugDetailReprot CityData)
        {


            string ImgPath = _configuration["ImgPath"];
            #region 第六章

            await managerWord.CreatePAsync(WordTemplate.Get0025(),
                     (p, run) =>
                     {
                         managerWord.OneTitle(p, run);
                     });



            Type drugType = typeof(DrugReport);
            await managerWord.CreatePAsync(WordTemplate.Get0026(sb =>
            {

                sb.Append($"本次监测中，我市{AreaDrug.Count}个监测点污水中");

                foreach (var item in drugType.GetProperties().Where(t => t.PropertyType == typeof(double)))
                {
                    double.TryParse(item.GetValue(CityDrug).ToString(), out double res);
                    if (res > 0)
                    {
                        double num = AreaDrug.Where(t => (double)item.GetValue(t) > 0).Count();
                        sb.Append($"{item.GetColName()}检出率为{num.GetPercentBySun(AreaDrug.Count)}%,{item.GetColName()}浓度在0.00~{res.SaveNumberPoint()}纳克/升范围内；");
                    }
                }
            }),
                   (p, run) =>
                   {
                       managerWord.Content(p, run);
                   });
            int ixy = 1;
            foreach (var item in drugType.GetProperties().Where(t => t.PropertyType == typeof(double)))
            {
                if (double.TryParse(item.GetValue(CityDrug).ToString(), out double res))
                {
                    if (res > 0)
                    {
                        string PropName = item.GetColName();

                        await managerWord.CreatePAsync(WordTemplate.Get0027(new string[] { $"{ixy}", PropName }),
                           (p, run) =>
                           {
                               run.FontSize = 14;
                               run.IsBold = true;
                               p.Style = "2";
                               run.FontFamily = "宋体";
                           });
                        managerWord.AddPic(@$"{ImgPath}\{CityData.CompanyID}\{CityData.Quarter}\SingleCol\{item.Name}_area.png", 600, 400);
                        await managerWord.CreatePAsync(WordTemplate.Get0029(managerWord.GetPicIndex(), PropName),
                       (p, run) =>
                       {
                           p.Alignment = ParagraphAlignment.CENTER;
                           managerWord.Content(p, run);
                       });

                        await managerWord.CreatePAsync(WordTemplate.Get0028(
                            AreaDrug.Select(t => new PieView() { Name = t.AreaName, Value = (double)item.GetValue(t) }).ToList(), (double)item.GetValue(CityDrug), PropName
                            ),
             (p, run) =>
             {
                 managerWord.Content(p, run);
             });
                        ixy++;

                    }
                }

            }
            #endregion
        }

        public async Task SevenSection(DrugDayView cityDrugDay, List<DrugDayView> areaData, List<DrugDayView> GroupDrugDays)
        {
            string ImgPath = _configuration["ImgPath"];
            #region 第七章
            Type drugDayType = typeof(DrugDayView);
            await managerWord.CreatePAsync(WordTemplate.Get0048(), (p, r) =>
            {
                managerWord.OneTitle(p, r);
            });

            await managerWord.CreatePAsync(WordTemplate.Get0049(), (p, r) =>
            {
                p.Alignment = ParagraphAlignment.CENTER;
                managerWord.Content(p, r);
                int count = GroupDrugDays.Count + 2;
                managerWord.CreateTable(count, 7, (table, doc) =>
                {
                    table.Width = 700 * 7 + 250;
                    table.SetColumnWidth(0, 950); /* 设置列宽 */
                    table.SetColumnWidth(1, 700); /* 设置列宽 */
                    table.SetColumnWidth(2, 700); /* 设置列宽 */
                    table.SetColumnWidth(3, 700); /* 设置列宽 */
                    table.SetColumnWidth(4, 700); /* 设置列宽 */
                    table.SetColumnWidth(5, 700); /* 设置列宽 */
                    table.SetColumnWidth(6, 700); /* 设置列宽 */

                    table.GetRow(0).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, "日消耗总量(克/天)"));


                    CT_Tc cttc = table.GetRow(0).GetCell(0).GetCTTc();
                    CT_TcPr ctPr = cttc.AddNewTcPr();
                    ctPr.AddNewVMerge().val = ST_Merge.restart;//合并行
                    ctPr.AddNewVAlign().val = ST_VerticalJc.center;//垂直


                    CT_Tc cttc_1 = table.GetRow(1).GetCell(0).GetCTTc();
                    CT_TcPr ctPr_1 = cttc_1.AddNewTcPr();
                    ctPr_1.AddNewVMerge().val = ST_Merge.@continue;//合并行
                    table.GetRow(0).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, "采样地点"));


                    int index = 1;
                    table.GetRow(0).MergeCells(1, 6); /* 合并行 */
                    foreach (var item in drugDayType.GetProperties().Where(t => t.PropertyType == typeof(double)))
                    {
                        string name = item.GetColName();

                        if (name.Contains("("))
                        {
                            name = name.Substring(0, name.IndexOf("("));
                            table.GetRow(1).GetCell(index).SetParagraph(managerWord.SetCellText(doc, table, name));
                            index++;
                        }

                    }
                    index = 2;
                    foreach (var item in areaData)
                    {
                        table.GetRow(index).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, item.MonitoringSite));
                        table.GetRow(index).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, item.Morphine.SaveNumberPoint()));
                        table.GetRow(index).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, item.Methylamphetamine.SaveNumberPoint()));
                        table.GetRow(index).GetCell(3).SetParagraph(managerWord.SetCellText(doc, table, item.Ketamine.SaveNumberPoint()));
                        table.GetRow(index).GetCell(4).SetParagraph(managerWord.SetCellText(doc, table, item.Cyclohexanone.SaveNumberPoint()));
                        table.GetRow(index).GetCell(5).SetParagraph(managerWord.SetCellText(doc, table, item.MDMA.SaveNumberPoint()));
                        table.GetRow(index).GetCell(6).SetParagraph(managerWord.SetCellText(doc, table, item.Cocaine.SaveNumberPoint()));
                        index++;
                    }

                    table.GetRow(index).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, "平均值"));
                    table.GetRow(index).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, cityDrugDay.Morphine.SaveNumberPoint()));
                    table.GetRow(index).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, cityDrugDay.Methylamphetamine.SaveNumberPoint()));
                    table.GetRow(index).GetCell(3).SetParagraph(managerWord.SetCellText(doc, table, cityDrugDay.Ketamine.SaveNumberPoint()));
                    table.GetRow(index).GetCell(4).SetParagraph(managerWord.SetCellText(doc, table, cityDrugDay.Cyclohexanone.SaveNumberPoint()));
                    table.GetRow(index).GetCell(5).SetParagraph(managerWord.SetCellText(doc, table, cityDrugDay.MDMA.SaveNumberPoint()));
                    table.GetRow(index).GetCell(6).SetParagraph(managerWord.SetCellText(doc, table, cityDrugDay.Cocaine.SaveNumberPoint()));

                });
            });




            await managerWord.CreatePAsync(WordTemplate.Get0050(managerWord.GetPicIndex()), (p, r) =>
            {
                p.Alignment = ParagraphAlignment.CENTER;
                managerWord.Content(p, r);

            });

            managerWord.AddPic(Path.Combine(ImgPath, cityDrugDay.CompanyID.ToString(), cityDrugDay.Quarter.ToString(), "day", $"{cityDrugDay.CompanyID}_day_{cityDrugDay.Quarter}.png"), 600, 580);

            foreach (var drugDayProp in drugDayType.GetProperties().Where(t => t.PropertyType == typeof(double) && t.GetColName().Contains("(")))
            {
                List<PieView> pies = new List<PieView>();
                string PropName = drugDayProp.GetColName();
                PropName = PropName.Substring(0, PropName.IndexOf("("));
                double.TryParse(drugDayProp.GetValue(cityDrugDay).ToString(), out double avg);
                foreach (var item in GroupDrugDays)
                {
                    double.TryParse(drugDayProp.GetValue(item).ToString(), out double res);
                    pies.Add(new PieView()
                    {
                        Name = item.AreaName,
                        Value = res
                    });
                }

                if (pies.Where(t => t.Value> 0 && !t.Name.Contains("无")).Any())
                {
                    await managerWord.CreatePAsync(WordTemplate.Get0051(pies.Where(t=>!t.Name.Contains("无")).ToList(), avg, PropName), (p, r) =>
                    {
                        managerWord.Content(p, r);
                    });
                }

            }

            #endregion
        }

        public async Task EndSection(string path, string FileName, DrugDetailReprot CityData, List<DrugUnion> drugs)
        {
            #region 末尾部分

            Type drugType = typeof(DrugReport);
            //添加四个空格
            await managerWord.CreatePAsync("",
               (p, run) =>
               {
                   for (int i = 0; i < 4; i++)
                   {
                       run.AddCarriageReturn();
                   }
               });
            await managerWord.CreatePAsync(WordTemplate.GetComponyName(),
                 (p, run) =>
                 {

                     p.Alignment = ParagraphAlignment.RIGHT;
                     managerWord.Content(p, run);
                 });
            await managerWord.CreatePAsync(WordTemplate.GetDate(new string[] { DateTime.Now.Year.ToString(),
                DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString() }),
               (p, run) =>
               {
                   p.Alignment = ParagraphAlignment.RIGHT;
                   managerWord.Content(p, run);
               });

            await managerWord.CreatePAsync("",
               (p, run) =>
               {
                   run.AddBreak();
               });

            await managerWord.CreatePAsync(WordTemplate.Get0035(CityData.AreaName),
             (p, run) =>
             {

                 managerWord.OneTitle(p, run);
                 int count = drugs.Count() + 2;
                 managerWord.CreateTable(count, 16, (table, doc) =>
                 {

                     table.Width = 350 * 16;
                     table.SetColumnWidth(0, 350); /* 设置列宽 */
                     table.SetColumnWidth(1, 350); /* 设置列宽 */
                     table.SetColumnWidth(2, 350); /* 设置列宽 */
                     table.SetColumnWidth(3, 350); /* 设置列宽 */
                     table.SetColumnWidth(4, 350); /* 设置列宽 */
                     table.SetColumnWidth(5, 350); /* 设置列宽 */
                     table.SetColumnWidth(6, 350); /* 设置列宽 */
                     table.SetColumnWidth(7, 350); /* 设置列宽 */
                     table.SetColumnWidth(8, 350); /* 设置列宽 */
                     table.SetColumnWidth(9, 350); /* 设置列宽 */
                     table.SetColumnWidth(10, 350); /* 设置列宽 */
                     table.SetColumnWidth(11, 350); /* 设置列宽 */
                     table.SetColumnWidth(12, 350); /* 设置列宽 */
                     table.SetColumnWidth(13, 350); /* 设置列宽 */
                     table.SetColumnWidth(14, 350); /* 设置列宽 */
                     table.SetColumnWidth(15, 350); /* 设置列宽 */


                     table.GetRow(0).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, "浓度（纳克/升）", 6));


                     CT_Tc cttc = table.GetRow(0).GetCell(0).GetCTTc();
                     CT_TcPr ctPr = cttc.AddNewTcPr();
                     ctPr.AddNewVMerge().val = ST_Merge.restart;//合并行
                     ctPr.AddNewVAlign().val = ST_VerticalJc.center;//垂直


                     CT_Tc cttc_1 = table.GetRow(1).GetCell(0).GetCTTc();
                     CT_TcPr ctPr_1 = cttc_1.AddNewTcPr();
                     ctPr_1.AddNewVMerge().val = ST_Merge.@continue;//合并行
                     table.GetRow(0).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, "采样地点", 6));


                     int index = 0;
                     table.GetRow(0).MergeCells(1, 15); /* 合并行 */
                     foreach (var item in drugType.GetProperties().Where(t => t.PropertyType == typeof(double)))
                     {
                         string name = item.GetColName();
                         table.GetRow(1).GetCell(index + 1).SetParagraph(managerWord.SetCellText(doc, table, name, 6));
                         index++;
                     }
                     index = 2;
                     int AreaID = 0;



                     foreach (var drug in drugs.ToList())
                     {

                         CT_Tc cttc_2 = table.GetRow(index).GetCell(0).GetCTTc();
                         CT_TcPr ctPr_2 = cttc_2.AddNewTcPr();
                         if (AreaID == drug.AreaID)
                         {
                             ctPr_2.AddNewVMerge().val = ST_Merge.@continue;//合并行
                         }
                         else
                         {
                             ctPr_2.AddNewVMerge().val = ST_Merge.restart;//合并行
                         }
                         AreaID = drug.AreaID;
                         table.GetRow(index).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, drug.AreaName, 6));
                         table.GetRow(index).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, drug.Morphine.MappingZero(), 6));
                         table.GetRow(index).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, drug.Codeine.MappingZero(), 6));
                         table.GetRow(index).GetCell(3).SetParagraph(managerWord.SetCellText(doc, table, drug.Methcathinone.MappingZero(), 6));
                         table.GetRow(index).GetCell(4).SetParagraph(managerWord.SetCellText(doc, table, drug.Monoacetylmorphine_06.MappingZero(), 6));
                         table.GetRow(index).GetCell(5).SetParagraph(managerWord.SetCellText(doc, table, drug.Benzedrine.MappingZero(), 6));
                         table.GetRow(index).GetCell(6).SetParagraph(managerWord.SetCellText(doc, table, drug.Methylamphetamine.MappingZero(), 6));
                         table.GetRow(index).GetCell(7).SetParagraph(managerWord.SetCellText(doc, table, drug.PMMA.MappingZero(), 6));
                         table.GetRow(index).GetCell(8).SetParagraph(managerWord.SetCellText(doc, table, drug.Ketamine.MappingZero(), 6));
                         table.GetRow(index).GetCell(9).SetParagraph(managerWord.SetCellText(doc, table, drug.NoKetamine.MappingZero(), 6));
                         table.GetRow(index).GetCell(10).SetParagraph(managerWord.SetCellText(doc, table, drug.Cyclohexanone.MappingZero(), 6));
                         table.GetRow(index).GetCell(11).SetParagraph(managerWord.SetCellText(doc, table, drug.MDA.MappingZero(), 6));
                         table.GetRow(index).GetCell(12).SetParagraph(managerWord.SetCellText(doc, table, drug.MDMA.MappingZero(), 6));
                         table.GetRow(index).GetCell(13).SetParagraph(managerWord.SetCellText(doc, table, drug.Benzoylecgonine.MappingZero(), 6));
                         table.GetRow(index).GetCell(14).SetParagraph(managerWord.SetCellText(doc, table, drug.Cocaine.MappingZero(), 6));
                         table.GetRow(index).GetCell(15).SetParagraph(managerWord.SetCellText(doc, table, drug.Cotinine.MappingZero(), 6));
                         index++;
                     }

                 });
             });
            await managerWord.CreatePAsync("", (p, run) =>
            {
                run.AddBreak();
            });
            await managerWord.CreatePAsync(WordTemplate.Get0036(),
            (p, run) =>
            {
                managerWord.OneTitle(p, run);
                Type type = typeof(DrugReport);

                managerWord.CreateTable(type.GetProperties().Where(t => t.PropertyType == typeof(double)).Count() + 1, 3,
                    (table, doc) =>
                    {
                        table.Width = 1500 * 3;
                        table.SetColumnWidth(0, 1500); /* 设置列宽 */
                        table.SetColumnWidth(1, 1500); /* 设置列宽 */
                        table.SetColumnWidth(2, 1500); /* 设置列宽 */
                        table.GetRow(0).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, "检测目标物", 14));
                        table.GetRow(0).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, "检出限（纳克/升）", 14));
                        table.GetRow(0).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, "定量限（纳克/升）", 14));
                        int index = 1;
                        foreach (var item in type.GetProperties().Where(t => t.PropertyType == typeof(double)).ToList())
                        {

                            if (item.GetColName().Contains("可替宁"))
                            {
                                table.GetRow(index).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, item.GetColName(), 14));
                                table.GetRow(index).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, "1.0", 14));
                                table.GetRow(index).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, "0.5", 14));
                            }
                            else
                            {
                                table.GetRow(index).GetCell(0).SetParagraph(managerWord.SetCellText(doc, table, item.GetColName(), 14));
                                table.GetRow(index).GetCell(1).SetParagraph(managerWord.SetCellText(doc, table, "0.5", 14));
                                table.GetRow(index).GetCell(2).SetParagraph(managerWord.SetCellText(doc, table, "1.0", 14));
                            }
                            index++;
                        }
                    }
                    );
            });

            managerWord.BuliderWorldAsync(path, FileName);
            #endregion
        }
    }
}
